<template>
  <div>
    <!-- 面包屑导航 -->
    <bread :item="['权限管理','角色列表']"></bread>
    <!-- 卡片视图 -->
    <el-card shadow="hover">
      <!-- 添加角色 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRole">添加角色</el-button>
        </el-col>
      </el-row>

    <!-- 角色列表 -->
      <el-table border stripe :data="roles" height="520">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom',i1===0 ?'bdtop':'','vcenter']" v-for="(item1,i1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row :class="[i2!==0 ? 'bdtop' :'','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                      <el-tag type="warning" closable v-for="item3 in item2.children" 
                              :key="item3.id" @close="removeById(scope.row,item3.id)">
                        {{item3.authName}}
                      </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="editRole(scope.row.id)"></el-button>
            <el-tooltip content="设置权限" placement="top" :enterable="false">
              <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRight(scope.row)"></el-button>
            </el-tooltip> 
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="delRole(scope.row.id)"></el-button>
          </template>
        </el-table-column>

      </el-table>

    </el-card>
    <!-- 编辑角色对话框 -->
  <el-dialog title="修改角色" :visible.sync="editDiolog"
               width="50%" >
    <el-form :model="oneRole" :rules="Rules" ref="editForm" label-width="100px">
      <el-form-item label="角色名称"  prop="roleName" >
       <el-input v-model="oneRole.roleName" :disabled="disable"></el-input>
      </el-form-item>
       <el-form-item label="角色描述" prop="roleDesc">
       <el-input v-model="oneRole.roleDesc" :disabled="disable"></el-input>
      </el-form-item>
    </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editDiolog = false" :disabled="disable">取 消</el-button>
    <el-button type="primary" @click="editDioClo" :disabled="disable">确 定</el-button>
  </span>
  </el-dialog>

<!-- 添加角色对话框 -->
  <el-dialog title="添加角色" :visible.sync="addRoleDialog"
               width="50%" @close="addRoleClose">
    <el-form :model="newRole" :rules="Rules" ref="addForm" label-width="100px">
      <el-form-item label="角色名称"  prop="roleName" >
       <el-input v-model="newRole.roleName" :disabled="disable"></el-input>
      </el-form-item>
       <el-form-item label="角色描述" prop="roleDesc">
       <el-input v-model="newRole.roleDesc" :disabled="disable"></el-input>
      </el-form-item>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="addRoleDialog = false" :disabled="disable">取 消</el-button>
      <el-button type="primary" @click="ykeoAdd" :disabled="disable">确 定</el-button>
    </span>
  </el-dialog>

  <!-- 设置权限对话框 -->
  <el-dialog title="设置权限" :visible.sync="setRights"
               width="50%" @close="clearSetKeys">

    <el-tree :data="rights" :props="treeProps" node-key="id" ref="tree" 
              show-checkbox :default-checked-keys="deKeys" default-expand-all></el-tree>

    <span slot="footer" class="dialog-footer">
      <el-button @click="setRights = false" :disabled="disable">取 消</el-button>
      <el-button type="primary" @click="allotRights" :disabled="disable">确 定</el-button>
    </span>
  </el-dialog>

  </div>
</template>

<script>
import {bread} from "tools"
export default {
  components:{bread}
 ,data(){return{
    disable:false
    // 角色列表数据
   ,roles:[]
   ,editDiolog:false
   ,addRoleDialog:false
   ,setRights:false
   //即将分配权限的角色id
   ,roleId:''
   //权限列表
   ,rights:[]
   //树形控件绑定数据
   ,treeProps:{
     label:"authName"
    ,children:"children"
   }
   ,deKeys:[]
   ,oneRole:{
     roleName:""
    ,roleDesc:""
   }
  ,Rules:{
     roleName:[
       {required:true,message:"不能为空",trigger:"blur"}
     ]
    ,roleDesc:[
      {required:true,message:"不能为空",trigger:"blur"}
    ]
   }
  ,newRole:{
    roleName:""
   ,roleDesc:""
  }
  }}
 ,created(){
   //初始数据获取
   this.getRoles()
 }
 ,methods:{
   async getRoles(){
     let {data:ret}= await this.$XHR.get('roles')
     //请求出错提示
     if(ret?.meta?.status!==200)return this.$message({type:"error"
        ,message:"获取角色失败"
        ,center:"center"
        })
      this.roles= ret?.data ? ret?.data : []
   }
  ,async editRole(n){
    let {data:ret}= await this.$XHR.get('roles/'+n)
    if(ret.meta.status!==200) return this.$message({
      type:"error"
     ,message:"获取失败!"
     ,center:"center"
     })
    this.oneRole= ret?.data ? ret?.data : {}
    this.editDiolog=true
  }
  //删除角色
  ,delRole(n){
    let [type,message,center]=["success","删除成功","center"]
    this.$confirm("这将会永久删除此角色","提示",{
      confirmButtonText:"确认"
     ,cancelButtonText:"取消"
     ,type:"warning"
    })
    .then(async h=>{
      let {data:ret}= await this.$XHR.delete("roles/"+n)
      if(ret?.meta?.status!==200){
       [type,message]=["error","删除失败"]
       return 
      }
      this.getRoles()
    },e=>{
      [type,message]=[null,"已取消删除"]
    })
    .finally(()=>{
      let all= type ?{type}:{}
      all.message=message
      all.center=center
      all.duration=1300
      this.$message(all)
    })
  }
  //确认编辑角色对话框
 ,async editDioClo(){
   this.disable=true
   let id= this.oneRole.roleId
   let {data:ret}= await this.$XHR.put('roles/'+id,this.oneRole)
   let [type,message,center]=["success","修改成功","center"]
   if(ret?.meta?.status!==200){
     [type,message]=["error","修改失败"]
   }
   setTimeout(()=>{
     this.$message({type,message,center,duration:1500})
     type && this.getRoles()
   },800)
   setTimeout(()=>{
     this.editDiolog=false
     this.disable=false
   },1500)
  }
  //显示角色对话框
 ,addRole(){
   this.addRoleDialog=true
  }
  //添加角色
 ,ykeoAdd(){
   this.disable=true
   //预检验
   this.$refs["addForm"].validate(async vaild=>{
     if(!vaild)return this.disable=false
     let [type,message,center]=["success","添加成功","center"]
     let {data:ret}= await this.$XHR.post("roles",this.newRole)
     if(ret?.meta?.status!==201){
       [type,message]= ["error","添加失败"]
     }  
     //延迟提示
     setTimeout(()=>{
       this.$message({type,message,center})
     },800)
      //延迟关闭
     setTimeout(()=>{
       if(type!=="error"){ this.addRoleDialog=false;this.getRoles()}
       this.disable=false
     },1300)
   })
 }
 //移除权限
 ,removeById(role,rid){
   this.$confirm("确定删除此权限","提示",{
     confirmButtonText:"确定"
    ,cancelButtomText:"取消"
    ,type:"warning"
   })
   .then(async h=>{
     //发出删除权限请求
     let {data:ret}= await this.$XHR.delete(`roles/${role.id}/rights/${rid}`)
     if(ret?.meta?.status!==200) return this.$notify({
      type:"error"
     ,title:"错误"
     ,message:"删除失败"
    })
      role.children=ret.data
    
   }).catch(()=>null)
 }
 //设置权限对话框
 ,async showSetRight(role){
   //保存id用于提交
   this.roleId=role.id
   //获取权限树
   let {data:ret}= await this.$XHR.get("rights/tree")
   if(ret?.meta?.status!==200) return this.$notify({
     type:"error"
    ,message:"获取权限失败"
    ,title:"错误"
   })
   this.rights=ret?.data ? ret?.data :[]
   this.getLastKeys(role,this.deKeys)
   this.setRights=true
 }
 //获取三级节点的id
 ,getLastKeys(node,nal){
   if(!node?.children){
    return nal.push(node.id)
   }
   node.children.forEach(item=>
     this.getLastKeys(item,nal)
   )
 }
 //权限对话框关闭后清空权限数组
 ,clearSetKeys(){
   this.deKeys=[]
 }
 //点击确定权限
 ,async allotRights(){
   this.disable=true
   const rids= [
     ...this.$refs['tree'].getCheckedKeys()
    ,...this.$refs['tree'].getHalfCheckedKeys()
   ].join(',')
  //未选择确定时提示
   if(!rids){
     this.$notify.info({message:"未选择权限",title:"提示"})
     this.disable=false
     return 
   }
   let {data:ret}= await this.$XHR.post(`roles/${this.roleId}/rights`,{rids})
   let [type,message,center]=["success","修改权限成功","center"]
   if(ret?.meta?.status!==200){
     [type,message]=["error","修改失败"]
   }
   setTimeout(()=>{
     this.$message({type,message,center})
     this.getRoles()
     this.setRights=false
     this.disable=false
   },800)
 }
 ,addRoleClose(){
   this.$refs['addForm'].resetFields()
 }
 }
}
</script>

<style lang="less" scoped>
.el-table{
  margin-top: 15px;
}

.el-tag{
  margin: 8px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>